package org.six11.ss.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.six11.ss.server.bean.Clue;
import org.six11.ss.server.bean.Theme;
import org.six11.util.adt.MultiState;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class ThemesWebActionHandler extends WebActionHandler {

  public ThemesWebActionHandler(String actionName, String jsp, MultiState ms) {
    super(actionName, jsp, ms);
  }

  /**
   * 
   */
  @Override
  public void handle(HttpServletRequest req, HttpServletResponse resp, ServletContext context)
      throws ServletException, IOException {
    
    // if I get a new_clue and a themeID, add a clue and add it to the given theme.
    String newClueName = req.getParameter("new_clue");
    String themeID = req.getParameter("themeID");
    if (newClueName != null && newClueName.length() > 0 && themeID != null && themeID.length() > 0) {
      Theme t = loadTheme(themeID);
      Clue newClue = new Clue();
      newClue.setName(newClueName);
      newClue.setTheme(t);
      getHibernate().save(newClue);
      t.getClues().add(newClue);
      bug("Made a new clue '" + newClue.getName() + " and added it to theme " + t.getName());
      error(req, "Added clue '" + newClue.getName() + "' to theme '" + t.getName() + "'");
    }
    
    // if the user provided a new_theme string, add it to the DB.
    String newThemeName = req.getParameter("new_theme");
    if (newThemeName != null && newThemeName.length() > 0) {
      Theme newTheme = new Theme();
      newTheme.setName(newThemeName);
      getHibernate().save(newTheme);
      log("Added new theme: '" + newTheme.getName() + "' (id: " + newTheme.getId() + "'");
      bug("Made a new theme '" + newTheme.getName() + "'");
      error(req, "Added theme '" + newTheme.getName() + "'");
    }

    // if the user is looking at a particular theme, get the list of clues.
    if (themeID != null && themeID.length() > 0) {
      Theme theme = loadTheme(themeID);
      req.setAttribute("theme", theme);
    } else {
      // load the 'themes' attribute with an ordered list of ThemeInfo objects.
      List<Theme> themes = getHibernate().createQuery("from Theme as theme order by id").list();
      List<ThemeInfo> themeInfo = new ArrayList<ThemeInfo>();
      for (Theme t : themes) {
        themeInfo.add(new ThemeInfo(t.getId() + "", t.getName(), t.getClues().size() + ""));
      }

      // this will trigger the 'enter a theme' and 'list of themes' UI elements
      req.setAttribute("themes", themeInfo);
    }
    forwardTo(jsp, req, resp, context);
  }

}
